/*
 * @Description: user状态管理模块
 * @Author: yue
 * @Date: 2022-08-29 19:02:46
 * @LastEditors: yue
 * @LastEditTime: 2022-08-29 21:50:55
 */

import { login, getUserInfo, getBaseUserInfo } from '@/api/user'
import { setToken, getToken, removeToken, setTokenTime } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  SET_TOKEN(state, payload) {
    state.token = payload
    setToken(payload)
  },
  REMOVE_TOKEN(state) {
    state.token = null
    removeToken()
  },

  SET_USERINFO(state, payload) {
    state.userInfo = payload
  },
  REMOVE_USERINFO(state) {
    state.userInfo = {}
  }
}
const actions = {
  // 登录
  async login({ commit }, payload) {
    const res = await login(payload)
    commit('SET_TOKEN', res)
    setTokenTime()
  },
  // 获取用户信息
  async getUserInfo({ commit }) {
    const res = await getUserInfo()
    const baseRes = await getBaseUserInfo(res.userId)
    commit('SET_USERINFO', { ...res, ...baseRes })
    return res
  },
  async logout({ commit }) {
    commit('REMOVE_TOKEN')
    commit('REMOVE_USERINFO')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
